<template>
  <div class="connect">
    <div class="connect_box">
      <el-form :inline="true" ref="formInline" :model="formInline" class="demo-form-inline">
        <el-form-item :label="$t('Order_module.Batch_number')">
          <!-- 批次号 -->
          <el-input v-model="formInline.manifestNo" :placeholder="$t('Order_module.Batch_number')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('Order_module.PRINT_STATUS')">
          <!-- 打印状态 -->
          <el-select v-model="formInline.printStatus":placeholder="$t('Order_module.PRINT_STATUS')">
              <el-option
                v-for="item in printStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item :label="$t('public.Timing')">
          <!-- 选择时间 -->
           <el-date-picker
                value-format='yyyy-MM-dd HH:mm:ss'
                v-model="formInline.dataTimevalue"
                type="datetimerange"
                range-separator="-"
                @change="dataTimeChange"
                :start-placeholder="$t('public.Timing')"
                :end-placeholder="$t('public.Timing')">
              </el-date-picker>
        </el-form-item>
          <el-button type="primary" @click="search" >{{$t('public.query')}}</el-button>
          <el-button @click="resetForm('formInline')">{{$t('public.resetting')}}</el-button>
        </el-form-item>
      </el-form>
      <div class="btns_ayyay">
        <!-- 打印 -->
         <el-button :loading="doPrintLoading"  @click="doPrint">{{$t('Order_module.Print_face_sheet')}}</el-button>
         <!-- 预览 -->
         <el-button :loading="doPreviewLoading"  @click="doPreview">{{$t('public.preview')}}</el-button>
         <!-- 导出面单 -->
         <!-- <el-button>{{$t('Order_module.Export_Face_Sheet')}}</el-button> -->

         <!-- 拉取单号 -->
         <el-button :loading="pullOrderNumLoading" @click="pullOrderNum()">{{$t('public.Pull_order_number')}}</el-button>
         <!-- 驱动下载 -->
         <el-button :loading="DownLoadFileLoading" @click="DownLoadFile">{{$t('Order_module.Driver_Download')}}</el-button>
      </div>
        <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column align="center" type="selection" width="55"> </el-table-column>
         <!-- // manifestNo: null//批次编号,
          // userName: null//用户名称,
          // successNum: null//拉取成功订单数,
          // failNum: null//拉取失败订单数,
          // printedNum: null//已打印订单数,
          // notPrintedNum: null//未打印订单数, -->
          <!--批次编号  -->
          <el-table-column align="center" prop="manifestNo" :label="$t('Order_module.Batch_number')"  min-width="180"> </el-table-column>
          <!-- 用户名称 -->
          <el-table-column align="center" prop="userName" :label="$t('Order_module.name')"  min-width="180"> </el-table-column>
          <!-- 订单总数 -->
          <el-table-column align="center" prop="orderNumbers" :label="$t('public.Total_number_of_Orders')"  min-width="180"> </el-table-column>
          <!-- 拉取成功订单数 -->
          <el-table-column align="center" prop="successNum" :label="$t('public.Number_of_successfully_pulled_orders')"  min-width="180"> </el-table-column>
          <!-- 拉取失败订单数 -->
          <el-table-column align="center" prop="failNum" :label="$t('public.Number_of_error_pulled_orders')"  min-width="180"> </el-table-column>
          <!-- 已打印订单数 -->
          <el-table-column align="center" prop="printedNum" :label="$t('public.Number_of_printed_orders')"  min-width="180"> </el-table-column>
          <!-- 未打印订单数 -->
          <el-table-column align="center" prop="notPrintedNum" :label="$t('public.Unprinted_orders')"  min-width="180"> </el-table-column>

        </el-table>
        <div style="margin-top: 20px;"></div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 50, 200, 400]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </div>
  </div>
</template>

<script>
  import {
    manifest_list,
    manifest_dataCheck,
    manifest_billing,
    expressWaybill_list,
    notifyPrintResult,

    caiNiaoPrint
  } from '@/api/wqzApi'
  export default {
    components: {},
    data() {
      return {
        pullOrderNumLoading:false,
        DownLoadFileLoading:false,
        doPrintLoading:false,
        doPreviewLoading:false,
        total:100,
        limit:10,
        page:1,
        tableData:[],
        index:null,
        uuid:null,
        select_table:[], //选中的批次
        printStatusList:[ //打印状态选项
          {label:this.$t('public.No_Print_head') , value:0},
          {label:this.$t('public.printed'), value:1}
        ],
        formInline:{
          printStatus:null,
          manifestNo:null,
          startTime:null,
          endTime:null,
          dataTimevalue:[]
        },
        socket:null,
        printers:null,
        defaultPrinter:null,
        waybillNO:'000000000000',
        printTaskId:0,
        print_logisticsNos:[],
        waybillTemplateURL:process.env.VUE_APP_BASE_API + '/printer/middle'
      }
    },

    created() {
    },
    mounted() {
      this.getList()
      this.doConnect()
    },
    destroyed() {

    },
    methods: {
      DownLoadFile(){
        // 驱动下载
        this.DownLoadFileLoading = true
        this.$export_down2(caiNiaoPrint() , [] , 'CNPrintClient' , '.exe' ).then(res=>{
          this.DownLoadFileLoading = false
        }).catch(err=>{
        })
      },
      search(){
        this.page = 1
        this.getList()
      },
      doConnect() {
          this.socket = new WebSocket('ws://127.0.0.1:13528');
          var result = "打印成功";
          var tmptaskID = "0";
          var that = this

          // 打开Socket
          that.socket.onopen = function (event) {
              // 监听消息
              that.socket.onmessage = function (event) {
                  var data = JSON.parse(event.data);
                  that.printers = data.printers;
                  that.defaultPrinter = data.defaultPrinter;
                  if (data.cmd == 'notifyPrintResult') {
                      var result = "打印成功";
                      if (data.taskID != tmptaskID) {
                          for (var i = 0; i < data.printStatus.length; i++) {
                              if (data.printStatus[i].status == 'failed') {
                                  result = "打印失败";
                                  break;
                              } else if (data.printStatus[i].status == 'canceled') {
                                  result = "取消打印任务";
                                  break;
                              }
                          }
                          tmptaskID = data.taskID;

                      }
                  } else if (data.cmd == "print") {
                      if (data.previewURL){
                        notifyPrintResult(that.print_logisticsNos).then(res=>{
                          console.log('打印成功')
                          window.open(data.previewURL);
                          that.getList()
                        })
                      }
                  }

              };
              // 监听Socket的关闭
              that.socket.onclose = function (event) {
                  console.log("打印机失去联系，请刷新网页重新连接");
              };
          };
          that.socket.onerror = function (event) {
              console.log("打印机出现问题,请联系客服");
          }
      },

       doPreview() {
          var arr = []
          this.doPreviewLoading = true

          this.select_table.forEach((item,index)=>{
            arr.push(item.manifestNo)
          })
          if(arr.length<=0){
            this.$message({
              type:'warning',
              message:this.$t('public.Please_select_id')
            })
            this.doPreviewLoading = false
            return
          }
         var data = {
            manifestNo:arr.join(',')
          }
        expressWaybill_list(data).then(res=>{
          var arrs = []
          res.list.forEach((item,index)=>{
                 var dataArr ={
                   documentID:this.waybillNO,
                   contents:[
                     {
                           templateURL: this.waybillTemplateURL,
                           signature: "MD:kw4V6Gtj/7ZasLyotby+HA==",
                           data:item
                     }
                   ]
                 }
                arrs.push(dataArr)
                this.print_logisticsNos = []
                this.print_logisticsNos.push(item.logisticsNo)
            })
            var printData = this.getPrintData(arrs);
            printData.task.preview = true;
            this.doPreviewLoading = false
            this.socket.send(JSON.stringify(printData));
          }).catch(err=>{
            this.doPreviewLoading = false
        })
      },
      //打印电子面单
       doPrint() {
            this.doPrintLoading = true
              var arr = []
              this.select_table.forEach((item,index)=>{
                arr.push(item.manifestNo)
              })
              if(arr.length<=0){
                this.$message({
                  type:'warning',
                  message:this.$t('public.Please_select_id')
                })
                this.doPrintLoading = false
                return
              }
             var data = {
                manifestNo:arr.join(',')
              }
            expressWaybill_list(data).then(res=>{
              var arrs = []
              res.list.forEach((item,index)=>{
                     var dataArr ={
                       documentID:this.waybillNO,
                       contents:[
                         {
                               templateURL: this.waybillTemplateURL,
                               signature: "MD:kw4V6Gtj/7ZasLyotby+HA==",
                               data:item
                         }
                       ]
                     }
                    arrs.push(dataArr)
                    this.print_logisticsNos = []
                    this.print_logisticsNos.push(item.logisticsNo)
                })
                var printData = this.getPrintData(arrs);
                this.doPrintLoading = false
                this.socket.send(JSON.stringify(printData));
              }).catch(err=>{
                this.doPrintLoading = false
            })
      },
      getPrintData(arr) {
        if(arr.length<=0){
            this.$message({
              type:'warning',
              message:this.$t('public.No_printing_information_is_available')
            })
            return
          }
          this.waybillNO = "123456789123";
          this.printTaskId = parseInt(1000 * Math.random());
          var request = {
              cmd: "print",
              requestID: "12345678901234567890",
              version: "1.0",
              task: {
                   taskID: '' + this.printTaskId,
                   preview: false,
                   printer: this.defaultPrinter,
                   notifyMode: "allInOne",
                   previewType:'pdf',
                   documents: arr
              }
          };
          return request;
      },
        getUUID(len, radix) {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;
            if (len) {
                for (var i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
            } else {
                var r;
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';
                for (var i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random() * 16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        },















      resetForm(formName) {
        this.formInline={
          printStatus:null,
          manifestNo:null,
          startTime:null,
          endTime:null,
          dataTimevalue:[]
        }
        this.getList()
      },
      dataTimeChange(e){
        if(e==null){
          this.formInline.startTime=''
          this.formInline.endTime=''
        }else{
          this.formInline.startTime=e[0]
          this.formInline.endTime=e[1]
        }
      },
     pullOrderNum(index=0 , uuid=''){
       this.pullOrderNumLoading = true
       var arr = []
       if(this.select_table.length<=0){
         this.$message({
           type:'warning',
          message:this.$t('public.Please_select_batch_number')
         })
         this.pullOrderNumLoading = false
         return
       }
       this.select_table.forEach((item,index)=>{
         arr.push(item.manifestNo)
       })
       var data = {
         manifestNos:arr,
         index:index,
         uuid:uuid
       }
       var that = this
       var res_code = null
       var res_msg = null
       manifest_dataCheck(data).then(res=>{
         this.pullOrderNumLoading = false
          manifest_billing(res.datas).then(req=>{
            res_code = req.code
            res_msg = req.msg
            if(res.code==200){
              if(req.code == 0){
                this.$message({
                  type:'success',
                  message:res_msg
                })
                that.getList()
              }else{
                this.$message({
                  type:'error',
                  message:res_msg
                })
              }
            }
            if(res.code == 0){
              if(req.code == 0){
                 this.pullOrderNum(res.index , res.uuid)
              }else{
                this.$message({
                  type:'error',
                  message:res_msg
                })
              }
            }
          })
       }).catch(err=>{
         this.pullOrderNumLoading = false
       })
     },
     manifest_billing(list){

     },
      getList(){
        var data = {
          page:this.page,
          limit:this.limit,
          printStatus:this.formInline.printStatus,
          manifestNo:this.formInline.manifestNo,
          startTime:this.formInline.startTime,
          endTime:this.formInline.endTime,
        }
        manifest_list(data).then(res=>{
          this.tableData = res.page.list
          this.total = res.page.totalCount
        })
      },
      handleSelectionChange(e){
        this.select_table = e
      },
      handleSizeChange(e){
        this.limit = e
        this.getList()
      },
      handleCurrentChange(e){
        this.page = e
        this.getList()
      }
    }
  }
</script>

<style scoped>
  @import url('Waybill_printing.css');
</style>
